const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const router = new Router();
// 库存余额表写期初数
router.post('/app/barCodeToInfo', async ctx => {
    let code = ctx.request.body.barCode;
    if (!code) {
        return ctx.err('请输入条码')
    }
    const options = {
        url: `https://jisutxmcx.market.alicloudapi.com/barcode2/query?barcode=${code}`, // 请求的URL
        method: 'GET', // 请求方法
        headers: {
            'Authorization': 'APPCODE e9e94a4886cf43c081e9948e9e57f982', // 设置请求头
        },
    };
    let goods = await db.models['goods'].findOne({
        where: {
            tenantId: ctx.user.tenantId,
            [Op.or]:{
                barCode: code,
                barCode1: code,
            }
        }
    })
    if (goods) {
        return ctx.suc('', {
            exist: true, // 已存在
            goods
        })
    }
    else {
        try {
            const response = await new Promise((resolve, reject) => {
                request(options, (error, response, body) => {
                    if (error) {
                        reject(error);
                    } else {
                        resolve(body);
                    }
                });
            });
            let res = JSON.parse(response)
            let spec = null
            // if(res.result.type) {
            //     if(res.result.type.indexOf('12') !== -1) {
            //         spec = 12
            //     }
            //     if(res.result.type.indexOf('24') !== -1) {
            //         spec = 24
            //     }
            //     if(res.result.type.indexOf('6') !== -1) {
            //         spec = 6
            //     }
            //     if(res.result.type.indexOf('16') !== -1) {
            //         spec = 16
            //     }
            //     if(res.result.type.indexOf('8') !== -1) {
            //         spec = 8
            //     }
            // }
            goods = {
                name: res.result.name,
                spec,
                barCode: code,
            }
            return ctx.suc('', {
                exist: false,
                goods
            })
        }
        catch (e) {
            return ctx.suc('', {
                exist: false,
                goods: {
                    name: '',
                    spec: null,
                    barCode: code
                }
            })
        }
    }
})
// 查询商品库存

module.exports = router;
